<template>
  <div class="home-product">
    <!-- 默认显示分类商品 -->
    <template v-if="!searchResults">
      <HomePanel 
        v-for="item in homeDataStore.homeData" 
        :key="item.id"
        :title="item.name"
      >
        <div class="box">
          <ul class="goods-list">
            <li v-for="goods in item.goodsList" :key="goods.id">
              <GoodsItem :goods="goods" />
            </li>
          </ul>
        </div>
      </HomePanel>
    </template>

    <!-- 有搜索结果时显示 -->
    <template v-else>
      <HomePanel title="搜索结果">
        <div class="box">
          <ul class="goods-list" v-if="searchResults.length">
            <li v-for="goods in searchResults" :key="goods.id">
              <GoodsItem :goods="goods" />
            </li>
          </ul>
          <div v-else class="empty">暂无相关商品</div>
        </div>
      </HomePanel>
    </template>
  </div>
</template>

<script setup>
import HomePanel from './HomePanel.vue'
import GoodsItem from './GoodsItem.vue'
import { useHomeDataStore } from '@/stores/HomeDataStore'
import { searchAPI } from "@/apis/home.js";
import { ref, watch } from 'vue';

const homeDataStore = useHomeDataStore()
const props = defineProps({ keyword: String });
const searchResults = ref(null); // 用于存储搜索结果

// 监听关键词变化
watch(
  () => props.keyword,
  async (newVal) => {
    if (newVal) {
      try {
        const res = await searchAPI(newVal);
        searchResults.value = res.data;
      } catch (error) {
        console.error('搜索失败:', error);
        searchResults.value = [];
      }
    } else {
      searchResults.value = null;
    }
  },
  { immediate: true }
);
</script>

<style scoped lang='scss'>
/* 保持原有样式不变 */
.home-product {
  background: #fff;
  margin-top: 20px;
  .box {
    display: flex;
    .goods-list {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      li {
        width: 240px;
        height: 300px;
        margin-right: 10px;
        margin-bottom: 10px;
        &:nth-last-child(-n + 5) {
          margin-bottom: 0;
        }
        &:nth-child(5n) {
          margin-right: 0;
        }
      }
    }
    .empty {
      width: 100%;
      padding: 100px 0;
      text-align: center;
      color: #666;
    }
  }
}
</style>